////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Iflytek-ZY-GCZX team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.qams.controller;

import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.qams.domain.Issue;
import com.iflytek.ci.qams.service.FullTextService;
import com.iflytek.framework.lucene.Searchs;
import com.iflytek.framework.web.mvc.PaginationParam;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import static com.iflytek.ci.qams.dto.IssueFulltext.PAGE_ONE;
import static com.iflytek.ci.qams.dto.IssueFulltext.PAGE_SIZE;
import static com.iflytek.ci.qams.dto.IssueFulltext.PAGE_ZERO;

/**
 * <p>
 * 全文检索控制器.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-11-24 8:10 PM
 * @since JDK 1.5
 */
@Controller
public class FullTextController extends BaseController {
	/** Serial version */
	private static final long serialVersionUID = 2182459557134670015L;
	/** 全文检索服务 */
	@Autowired
	private FullTextService fullTextService;

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String search(@PaginationParam(required = false) PaginationCriteria criteria,
						 String q, Integer titles_only,
						 Model model) {
		if (criteria == null) {
			criteria = new PaginationCriteria(PAGE_ONE, PAGE_SIZE, null, null);
		} else {
			criteria.setStart(criteria.getStart() == PAGE_ZERO ? PAGE_ONE : criteria.getStart() / criteria.getNumber() + PAGE_ONE);
			criteria.setNumber(criteria.getNumber() == PAGE_ZERO ? PAGE_SIZE : criteria.getNumber());
		}
		final PaginationResult<Issue> issues = fullTextService.search(criteria, q,titles_only);
		model.addAttribute(Searchs.COUNT_MAP_KEY, issues.getTotal());
		model.addAttribute(Searchs.DOCUMENT_MAP_KEY, issues.getRows());
		//当前页码
		int page_current = criteria.getStart();
		//总页数
		int page_count = issues.getTotal() / PAGE_SIZE + PAGE_ONE;
		//是否存在下一页
		boolean hasNext = page_current < page_count;
		model.addAttribute("hasNext", hasNext);
		model.addAttribute("q", q);
		model.addAttribute("next", page_current + PAGE_ONE);
		//是否存在上一页
		boolean hasPrevious = page_current > PAGE_ONE;
		model.addAttribute("hasPre", hasPrevious);
		model.addAttribute("previous", page_current - PAGE_ONE);
		//选项设置
		model.addAttribute("only_title",(titles_only != null && titles_only==PAGE_ONE));
		return "search";
	}
}
